<template>
	<div id="trade-view"></div>
</template>

<script>
	import { widget } from '../../static/charting_library/charting_library.min.js'
	import datafeeds from '@/assets/js/datafees.js'

	export default {
		data() {
			return {
				symbol: 'LTC_USDT',
				interval: '15min',
				chart: null,
				initdata:{},
				countDate: 0, //累加条数
				startData: 0, //起始条数
				lengsData: 200, //结束长度
				datafeeds: new datafeeds(this),
				onLoadedCallback: null, //初始数据回调
				onRealtimeCallback: null, //websocket数据回调
			}
		},
		
		created() { },
		
		methods: {

			filter(time) {

				if(time == '1min')
					return '1';

				else if(time == '5min')
					return '5';

				else if(time == '15min')
					return '15';

				else if(time == '30min')
					return '30';

				else if(time == '60min')
					return '60';

				else if(time == '1day')
					return '1D';

				else if(time == '1week')
					return '1W';

				else if(time == '1mon')
					return '1M';
			},
			
			//ajax
			getBars(symbolInfo, resolution, rangeStartDate, rangeEndDate, onLoadedCallback) {
				this.onLoadedCallback = onLoadedCallback; this.getAjaxData();
			},

			//socket
			subscribeBars(symbolInfo, resolution, onRealtimeCallback, subscriberUID, onResetCacheNeededCallback) {
				this.onRealtimeCallback = onRealtimeCallback; this.webSocket();
			},

			//获取配置信息
			getSymbol(symbol) {
				return {
					'name': symbol,
					'full_name': symbol,
					'timezone': 'Asia/Shanghai',
					'minmov': 1,
					'minmov2': 0,
					'pointvalue': 1,
					'fractional': false,
					'session': '24x7',
					'has_intraday': true,
					'has_no_volume': false,
					'description': symbol,
					'pricescale': 100000000,
					'ticker': symbol,
				}
			},

			//设置品信息(重新获取初始数据/推送数据)
			setSymbols() {
				let self = this;
				self.chart.setSymbol(self.symbol, self.filter(self.interval),function(){
					self.chart.chart().setVisibleRange(self.initdata)
					self.chart.chart().executeActionById("timeScaleReset");
				});
			},
			
			//卸载K线
			removeChart() {
				if (this.chart) {
					this.chart.remove();
					this.chart = null;
				}
            },
			
			//加载K线图插件
			loadChart() {

				let self = this;

				this.chart = new widget({
					container_id: 'trade-view',
					symbol: self.symbol,
					interval: self.filter(self.interval),
					locale: 'zh',
					autosize: true,
					fullscreen: true,
					preset: "mobile",
					toolbar_bg: '#1e2235',
					datafeed: this.datafeeds,
					timezone: 'Asia/Shanghai',
					library_path: '/static/charting_library/',
					indicators_file_name: "custom-study(MACD红绿).js",
					drawings_access: {type: 'black',tools: [{name: "Regression Trend"}]},
					overrides: self.overrides(),
					//启用的功能
					enabled_features: [
						'adaptive_logo',//小屏幕上隐藏 'charts byTradingView' 文本
						'dont_show_boolean_study_arguments',//是否隐藏指标参数
						'hide_last_na_study_output',//隐藏最后一次指标输出
						'move_logo_to_main_pane',//logo在中间位置
						'same_data_requery',//允许您使用相同的商品调用 setSymbol 来刷新数据
						'hide_left_toolbar_by_defaul',//第一次打开图表时隐藏左工具栏
						'side_toolbar_in_fullscreen_mode',//使用此功能，您可以在全屏模式下启用绘图工具栏
						'disable_resolution_rebuild',//显示的时间与得到的数据时间一致
					],

					//面板上禁用的功能
					disabled_features: [
						"symbol_info",//商品信息对话框
						"timezone_men",//商品信息对话框禁用时区上下文菜单
						"go_to_date",//前往到（选时间段）
						"compare_symbol",//菜单中删除“比较/覆盖”对话框
						"left_toolbar", //左侧工具栏
						"pane_context_menu", //图标右键菜单
						"volume_force_overlay",//在主数据列的同一窗格上放置成交量指示器
						"pane_context_menu",
						"contextmenu",
						"scales_context_menu",
						"legend_context_menu",
						"display_market_status",
						"timeframes_toolbar", //底部时间栏
						"snapshot_trading_drawings",//包含屏幕截图中的订单/位置/执行信号
						"use_localstorage_for_settings",//允许将用户设置保存到localstorage
						"header_symbol_search", //搜索框
						"header_undo_redo", //头部左右箭头
						"header_compare",//头部对比信息按钮
						"header_settings", //设置按钮
						"header_resolutions", //时间选择、分时切换
						"header_screenshot", //截图相机
//						"header_fullscreen_button", //全屏按钮
//						"header_indicators", //指标
//						"header_chart_type",//图表类型切换 
					],

					studies_overrides: {

						//柱状图颜色
						"volume.volume.color.0": "rgba(255, 15, 93,0.6)",
						"volume.volume.color.1": "rgba(21,195,34,0.6)",

						//MACD样式
//						"MACD.MACD.color":"#F00",
//						"MACD.Signal.color":"#fe8",
//						"MACD.Histogram.color":"#0f0",
//						'MACD.MACD.linewidth':1,

					},

					
				});

				this.chart.onChartReady(function() {
					try {
						self.chart.chart().createStudy("Moving Average", !1, !1, [7], null, {});
						self.chart.chart().createStudy("Moving Average", !1, !1, [10], null, {});
						self.chart.chart().createStudy("Moving Average", !1, !1, [30], null, {});
						self.chart.chart().createStudy("MACD", !1, !1, [20], null, {});//MACD
						self.chart.chart().createStudy('指数平滑异同移动平均线(MACD_Custom)', false, false, [20], null, {});//自定义MACD
					} catch(e) {}
				})

			},

			overrides() {
            	let style = {
					up: "#178025",
					down: "#a31449",
					bg: "#1d1d29",
					grid: "#1e2235",
					cross: "#9194A3",
					border: "#4e5b85",
					borderUpColor: "rgba(21,195,34,0.9)",
					borderDownColor: "rgba(255, 15, 93,0.9)",
					text: "#61688A",
					areatop: "rgba(122, 152, 247, .2)",
					areadown: "rgba(122, 152, 247, .02)"
                };

            	return {
            		
					"volumePaneSize": "medium",//指标区域大小（large, medium, small, tiny）
					"scalesProperties.lineColor": style.text,
					"scalesProperties.textColor": style.text,
					"paneProperties.background": style.bg,//整体背景颜色
					"paneProperties.vertGridProperties.color": style.grid,//竖直网格线颜色
					"paneProperties.horzGridProperties.color": style.grid,//水平网格线颜色
					"paneProperties.crossHairProperties.color": style.cross,
					"paneProperties.legendProperties.showLegend":false,//收起左上角指标
					"paneProperties.legendProperties.showStudyArguments": true,
					"paneProperties.legendProperties.showStudyTitles": true,
					"paneProperties.legendProperties.showStudyValues": true,
					"paneProperties.legendProperties.showSeriesTitle": true,
					"paneProperties.legendProperties.showSeriesOHLC": true,
					"mainSeriesProperties.showPriceLine": false,//最新价格线
					"mainSeriesProperties.candleStyle.upColor": style.up,
					"mainSeriesProperties.candleStyle.downColor": style.down,
					"mainSeriesProperties.candleStyle.drawWick": true,
					"mainSeriesProperties.candleStyle.drawBorder": true,
					"mainSeriesProperties.candleStyle.borderColor": style.border,
					"mainSeriesProperties.candleStyle.borderUpColor": style.borderUpColor,
					"mainSeriesProperties.candleStyle.borderDownColor": style.borderDownColor,
					"mainSeriesProperties.candleStyle.wickUpColor": style.up,
					"mainSeriesProperties.candleStyle.wickDownColor": style.down,
					"mainSeriesProperties.candleStyle.barColorsOnPrevClose": false,
					"mainSeriesProperties.hollowCandleStyle.upColor": style.up,
					"mainSeriesProperties.hollowCandleStyle.downColor": style.down,
					"mainSeriesProperties.hollowCandleStyle.drawWick": true,
					"mainSeriesProperties.hollowCandleStyle.drawBorder": true,
					"mainSeriesProperties.hollowCandleStyle.borderColor": style.border,
					"mainSeriesProperties.hollowCandleStyle.borderUpColor": style.borderUpColor,
					"mainSeriesProperties.hollowCandleStyle.borderDownColor": style.borderDownColor,
					"mainSeriesProperties.hollowCandleStyle.wickColor": style.line,
					"mainSeriesProperties.haStyle.upColor": style.up,
					"mainSeriesProperties.haStyle.downColor": style.down,
					"mainSeriesProperties.haStyle.drawWick": true,
					"mainSeriesProperties.haStyle.drawBorder": true,
					"mainSeriesProperties.haStyle.borderColor": style.border,
					"mainSeriesProperties.haStyle.borderUpColor": style.borderUpColor,
					"mainSeriesProperties.haStyle.borderDownColor": style.borderDownColor,
					"mainSeriesProperties.haStyle.wickColor": style.border,
					"mainSeriesProperties.haStyle.barColorsOnPrevClose": false,
					"mainSeriesProperties.barStyle.upColor": style.up,
					"mainSeriesProperties.barStyle.downColor": style.down,
					"mainSeriesProperties.barStyle.barColorsOnPrevClose": false,
					"mainSeriesProperties.barStyle.dontDrawOpen": false,
					"mainSeriesProperties.lineStyle.color": style.border,
					"mainSeriesProperties.lineStyle.linewidth": 1,
					"mainSeriesProperties.lineStyle.priceSource": "close",
					"mainSeriesProperties.areaStyle.color1": style.areatop,
					"mainSeriesProperties.areaStyle.color2": style.areadown,
					"mainSeriesProperties.areaStyle.linecolor": style.border,
					"mainSeriesProperties.areaStyle.linewidth": 1,
					"mainSeriesProperties.areaStyle.priceSource": "close",
				};
            },

			//ajax获取初始数据
			getAjaxData() {

				let self = this;
				
				$.ajax({
					type: 'POST',
					url: 'http://localhost:8080/api/TradingHall/macket/getKDataList',
					data: {
						dealPair: self.symbol,
						ktype: self.interval,
						startNo: (self.startData + self.countDate),
						endNo: (self.startData + self.lengsData),
					},
					traditional: true,
					success: function(result) {

						let
							bars = [],
							data = result.data.reverse();
						
						if(self.startData == 0){
							self.initdata.form = data[0].ktime;
							self.initdata.to   = data[0].ktime;
						}
						
						data.forEach(item => {

							let newObj = {
								time: item.ktime,
								open: item.openingPrice,
								close: item.closingPrice,
								high: item.topPrice,
								low: item.floorPrice,
								volume: item.dealQuantity
							}

							bars.push(newObj)
						})

						self.startData = self.startData + self.lengsData + self.countDate + 1;
						self.onLoadedCallback(bars);
					}
				})

			},

			//获取推送数据
			webSocket() {

				let self = this;

				try {this.websock.close()} catch(e) {}
				this.websock = new WebSocket('ws://www.7ebit.biz/websocket/' + self.symbol);
				this.websock.onmessage = res => {

					let data = JSON.parse(res.data);
					let type = data.datatype; //数据推送方式
					let time = data.data.ktype; //分时类型
					let coin = data.data.dealPair; //币类型

					if(type == 'tick') return;

					let d = data.data;

					if(d) {
						try {
							let dise = {
								time: d.ktime,
								open: d.openingPrice,
								close: d.closingPrice,
								high: d.topPrice,
								low: d.floorPrice,
								volume: d.dealQuantity
							};

							self.onRealtimeCallback(dise)
						} catch(e) {}
					}
				}
			}
		},

		mounted() {
			
			//加载K线图
			this.loadChart();

			let self = this;
			
			//测试切换商品，3秒后切换商品类型更新数据
			setTimeout(function() {

				self.symbol = 'ETH_USDT';
				self.interval = '1min';
				//更新数据重置ajax参数
				self.countDate = 0; //累加条数
				self.startData = 0; //起始条数
				self.lengsData = 200; //结束长度
				self.setSymbols();
				//设置分时
				//self.chart.chart().setChartType(3);
				console.log('123----')
			}, 15000)
		}
	}
</script>